import 'package:app/models/response/videos_response.dart';
import 'package:app/pages/tikvideo/widget/tikTokScaffold.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'tikvideo_controller.dart';
import 'widget/physycs.dart';
import 'widget/tikTokCommentBottomSheet.dart';
import 'widget/tikTokVideo.dart';
import 'package:video_player/video_player.dart';
import 'widget/tikTokVideoButtonColumn.dart';
import 'widget/tikTokVideoListController.dart';
import 'package:safemap/safemap.dart';

/// 单独修改了bottomSheet组件的高度
import '../components/bottomSheet.dart' as CustomBottomSheet;

class TikVideoScreen extends StatefulWidget with WidgetsBindingObserver {
  TikVideoScreen({Key? key}) : super(key: key);

  @override
  _TikVideoScreenState createState() => _TikVideoScreenState();
}

class _TikVideoScreenState extends State<TikVideoScreen>
    with WidgetsBindingObserver {
  TikTokScaffoldController tkController = TikTokScaffoldController();
  PageController _pageController = PageController();

  TikTokVideoListController _videoListController = TikTokVideoListController();

  /// 点赞
  Map<int, bool> favoriteMap = {};
  List<VideoData> videoDataList = [];

  final GetxController = Get.find<VideoControllerGetx>();

  Future _getList() async {
    videoDataList = await GetxController.getVideos();

    _videoListController.init(
      pageController: _pageController,
      initialList: videoDataList
          .map(
            (e) => VPVideoController(
              videoInfo: e,
              builder: () =>
                  VideoPlayerController.network(e.toJson()["video"]["url"]),
            ),
          )
          .toList(),
      videoProvider: (int index, List<VPVideoController> list) async {
        return videoDataList
            .map(
              (e) => VPVideoController(
                videoInfo: e,
                builder: () =>
                    VideoPlayerController.network(e.toJson()["video"]["url"]),
              ),
            )
            .toList();
      },
    );
    _videoListController.addListener(() {
      setState(() {});
    });
    tkController.addListener(
      () {
        if (tkController.value == TikTokPagePositon.middle) {
          _videoListController.currentPlayer.play();
        } else {
          _videoListController.currentPlayer.pause();
        }
      },
    );
  }

  @override
  initState() {
    WidgetsBinding.instance!.addObserver(this);
    _getList();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return _buildFuture();
  }

  Widget _buildFuture() {
    Widget? currentPage;
    double a = MediaQuery.of(context).size.aspectRatio;
    bool hasBottomPadding = a < 0.55;

    return TikTokScaffold(
      controller: tkController,
      header: Container(),
      enableGesture: true,
      page: Stack(
        children: [
          PageView.builder(
              key: Key("TikVideoScreen"),
              physics: QuickerScrollPhysics(),
              controller: _pageController,
              scrollDirection: Axis.vertical,
              itemCount: _videoListController.videoCount,
              itemBuilder: (context, i) {
                //拼接一个视频出来
                bool isF = SafeMap(favoriteMap)[i].boolean;
                var player = _videoListController.playerOfIndex(i)!;
                var data = player.videoInfo!.toJson();
                //右侧按钮列表
                Widget buttons = TikTokButtonColumn(
                  isFavorite: isF,
                  userAvatar: data["user"]["image"],
                  likes: data["likes"],
                  comments: data["comments"],
                  collects: data["collects"],
                  onAvatar: () {
                    // tkController.animateToPage()
                  },
                  onFavorite: () {
                    setState(() {
                      favoriteMap[i] = !isF;
                    });
                  },
                  onComment: () {
                    CustomBottomSheet.showModalBottomSheet(
                      backgroundColor: Colors.white.withOpacity(0),
                      context: context,
                      builder: (BuildContext context) =>
                          TikTokCommentBottomSheet(),
                    );
                  },
                  onShare: () {},
                );

                Widget currentVideo = Center(
                  child: AspectRatio(
                    aspectRatio: player.controller.value.aspectRatio,
                    child: VideoPlayer(player.controller),
                  ),
                );
                currentVideo = TikTokVideoPage(
                  hidePauseIcon: !player.showPauseIcon.value,
                  aspectRatio: 9 / 16.0,
                  video: currentVideo,
                  key: Key(data["video"]["id"]),
                  tag: data["title"],
                  onAddFavorite: () {
                    setState(() {
                      favoriteMap[i] = true;
                    });
                  },
                  userInfoWidget: VideoUserInfo(
                    desc: data["desc"],
                    title: data["title"],
                    nickName: data["user"]["nickname"],
                    // nickName: data["user"]["nickname"],
                    bottomPadding: hasBottomPadding ? 16.0 : 50.0,
                  ),
                  onSingleTap: () async {
                    if (player.controller.value.isPlaying) {
                      await player.pause();
                    } else {
                      await player.play();
                    }
                    setState(() {});
                  },
                  rightButtonColumn: buttons,
                );
                return currentVideo;
              }),
          currentPage ?? Container()
        ],
      ),
    );
  }

  void didChangeAppLifecycleState(AppLifecycleState state) async {
    if (state != AppLifecycleState.resumed) {
      _videoListController.currentPlayer.pause();
    }
  }

  @override
  void dispose() {
    WidgetsBinding.instance!.removeObserver(this);
    _videoListController.currentPlayer.pause();
    super.dispose();
  }
}
